package com.android.fragmentdemo.definervlayoutmanager
import android.content.Context
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager

class DefineGridLayoutManager(context: Context, spanCount: Int) :
    GridLayoutManager(context, spanCount) {

    override fun onInterceptFocusSearch(focused: View, direction: Int): View? {
        val position = getPosition(focused)
        when (direction) {
            View.FOCUS_UP -> {
                if (position - spanCount >= 0) {
                    return findViewByPosition(position - spanCount)
                }
            }
            View.FOCUS_DOWN -> {
                if (position + spanCount < itemCount) {
                    return findViewByPosition(position + spanCount)
                }
            }
            View.FOCUS_LEFT -> {
                if (position % spanCount != 0) {
                    return findViewByPosition(position - 1)
                }
            }
            View.FOCUS_RIGHT -> {
                if ((position + 1) % spanCount != 0 && (position + 1) < itemCount) {
                    return findViewByPosition(position + 1)
                }
            }
        }
        return super.onInterceptFocusSearch(focused, direction)
    }

}